import 'package:Sayagh/Configs.dart';
import 'package:sqflite/sqflite.dart';

class Kala {
  int id;
  int updateDate = new DateTime.now().millisecondsSinceEpoch;
  String city;
  String tableName;
  String code;
  String name;
  int price;
  String describe;
  String unit;
  String category;
  int stateCode;
  int cityCode;
  int categoryCode;
  int kalaCode;

  Kala();

  Kala.fromMap(Map<String, dynamic> _kala) {
    id = _kala["id"];
    updateDate = _kala["updateDate"];
    city = _kala["city"];
    tableName = _kala["tableName"];
    code = _kala["code"];
    name = _kala["name"];
    price = _kala["price"];
    describe = _kala["describe"];
    unit = _kala["unit"];
    category = _kala["category"];
    stateCode = _kala["stateCode"];
    cityCode = _kala["cityCode"];
    categoryCode = _kala["categoryCode"];
    kalaCode = _kala["kalaCode"];
  }

  Kala.fromList(List<dynamic> _kala, _tableName, _updateDate, _city) {
    if (_kala.length < 6) return;
    _updateDate == null
        ? updateDate = new DateTime.now().millisecondsSinceEpoch
        : updateDate = _updateDate;
    city = _city;
    tableName = _tableName;
    code = _kala.removeAt(0);
    name = _kala.removeAt(0);
    var _price = _kala.removeAt(0);
    try {
      price = int.parse(_price);
    } catch (e) {
      price = 0;
    }
    describe = _kala.removeAt(0);
    unit = _kala.removeAt(0);
    category = _kala.removeAt(0);
    try {
      stateCode = int.parse(_kala.removeAt(0));
      cityCode = int.parse(_kala.removeAt(0));
      categoryCode = int.parse(_kala.removeAt(0));
      kalaCode = int.parse(_kala.removeAt(0));
    } catch (e) {
      print("kalaFromList");
      print(e);
    }
  }

  Map<String, dynamic> toMap() {
    Map<String, dynamic> _kala = {
      "updateDate": updateDate,
      "city": city,
      "tableName": tableName,
      "code": code,
      "name": name,
      "price": price,
      "describe": describe,
      "unit": unit,
      "category": category,
      "stateCode": stateCode,
      "cityCode": cityCode,
      "categoryCode": categoryCode,
      "kalaCode": kalaCode,
    };
    id != null ? _kala["id"] = id : id = null;
    return _kala;
  }
}

class KalaProvider {
  Database db;

  Future open() async {
    db = await openDatabase(ourDatabase, version: 1);
  }

  Future<Kala> insert(Kala kala) async {
    if (db == null || !db.isOpen) await open();
    kala.id = await db.insert(kalaTable, kala.toMap());
//    db.close();
    return kala;
  }
}
